package com.mediacloud.app.newsmodule.fragment.ws

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.eventTrack.TXReportManager
import com.google.gson.Gson
import com.mediacloud.app.fbnavsk.SecondNav
import com.mediacloud.app.model.activity.BaseBackActivity
import com.mediacloud.app.model.component.ComponentItem
import com.mediacloud.app.model.fragment.BaseFragment
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.model.news.kt.TypeX
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.adaptor.component.IExposure
import com.mediacloud.app.newsmodule.fragment.ListPreLoadKit
import com.mediacloud.app.newsmodule.fragment.video.vod.PlayClickListener
import com.mediacloud.app.newsmodule.fragment.video.x.RVListVideoKit
import com.mediacloud.app.newsmodule.utils.BindEventBus
import com.mediacloud.app.newsmodule.utils.VideoAddressGet
import com.mediacloud.app.reslib.enums.XKey
import com.mediacloud.app.reslib.util.DataInvokeUtil
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener
import com.tencent.mmkv.MMKV
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_info_flow.*
import kotlinx.android.synthetic.main.fragment_ws24.*
import kotlinx.android.synthetic.main.fragment_ws24.refreshLayout
import kotlinx.android.synthetic.main.ws24_list_fragment2.*
import kotlinx.android.synthetic.main.ws24_list_fragment2.recyclerView
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.*

class WS24ListFragment2 : BaseFragment(), OnLoadMoreListener, IExposure {
    companion object {
        fun newInstance(
            id: String,
            catalog: CatalogItem? = null,
            d: String? = null
        ): WS24ListFragment2 {
            val f = WS24ListFragment2()
            val b = Bundle()
            b.putString("DATE", d)
            b.putString("NAV_ID", id)
            catalog?.let {
                b.putParcelable("CATALOG", catalog)
            }
            f.arguments = b
            return f
        }
    }

    val sdf0 = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA)
    val sdf1 = SimpleDateFormat("yyyy.MM.dd", Locale.CHINA)
    val sdf2 = SimpleDateFormat("yyyy年MM月dd日", Locale.CHINA)
    val sdf3 = SimpleDateFormat("M月d日 HH:mm", Locale.CHINA)
    val sdf4 = SimpleDateFormat("HH:mm", Locale.CHINA)
    var publish_date_start: String? = null
    var publish_date_end: String? = null
    var refreshLayout: SmartRefreshLayout? = null
    private var mRVListVideoKit: RVListVideoKit? = null


    //var dataInvoker: NewsListDataInvoker? = null
    var adapter: WS24VideoListAdapter? = null

    protected var pageSize = 100
    var catalogID: String? = ""
    var cacheCatalogID: String? = ""

    var catalog: CatalogItem? = null

    var group_date_time = 0L
    var group_date_time_fromat: String? = null
    var preLoadKit: ListPreLoadKit<MutableList<Any>>? = null

    var manager: LinearLayoutManager? = null;

    private var scrollListener: RecyclerView.OnScrollListener? = null
    override fun getLayoutResID(): Int {
        return R.layout.ws24_list_fragment2
    }

    /*    override fun getLayoutView(): View? {
            return FragmentPreInflateHelper.getInstance(context).getView(layoutResID, javaClass)
        }*/

    //    fun refresh(publish_date_start: String?, publish_date_end: String?) {
//        this.publish_date_start = publish_date_start
//        this.publish_date_end = publish_date_end
//
//        getData()
//        // getNewsListData()
//    }
    val color1 = Color.parseColor("#666666")

    override fun initView() {
        catalogID = arguments?.getString("NAV_ID")
        catalog = arguments?.getParcelable("CATALOG")
        this.publish_date_start = arguments?.getString("DATE")
        this.publish_date_end = this.publish_date_start
        loadingView = findViewById(R.id.mLoadingView)
        initStateView()
        showStateView(BaseBackActivity.TYPE_LOADING, false)
        adapter = WS24VideoListAdapter(requireContext())
        manager = LinearLayoutManager(requireContext())
        recyclerView.layoutManager = manager
        recyclerView.adapter = adapter
        mRVListVideoKit = RVListVideoKit(requireContext(), recyclerView, this)

        val parentFragment = parentFragment as WS24Fragment
        if (refreshLayout == null) {
            refreshLayout = parentFragment.refreshLayout
        }

        if (preLoadKit == null) {

            preLoadKit = object :
                ListPreLoadKit<MutableList<Any>>(requireContext(), refreshLayout!!) {
                override fun onSetData(data: MutableList<Any>) {
                    setData(data)
                }

                override fun onPreload(preNum: Int) {
                    preload(preNum)
                }
            }
        }

        if (scrollListener == null) {
            scrollListener = object : RecyclerView.OnScrollListener() {
                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    super.onScrollStateChanged(recyclerView, newState)
                }

                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)
                    val position = manager!!.findFirstVisibleItemPosition()
                    val lastVisibleItem = manager!!.findLastVisibleItemPosition()
                    if (manager!!.itemCount > 1 && lastVisibleItem == manager!!.itemCount - 1) {
                        preLoadKit?.onLoadMore()
                    }
                    if (adapter!!.items.isNullOrEmpty()) return
                    adapter?.items?.get(position)?.let {
                        if (it is TimeLineItem) {
                            group_date_time = it.group_date_time
                            group_date_time_fromat = it.group_date_time_fromat
                            parentFragment.changeDate()
                        }
                    }
                }
            }
        }
        recyclerView.addOnScrollListener(scrollListener!!)
        getData()
        BindEventBus(this, adapter)
    }


    fun refresh() {
        mDisposable?.dispose()
        preloadDisposable?.dispose()
        preLoadKit?.onRefresh()
        mRVListVideoKit?.reset()
        getData()
    }

    var mDisposable: Disposable? = null

    @SuppressLint("SuspiciousIndentation")
    fun getData() {
        val map: MutableMap<String, String> = HashMap()
        if (!TextUtils.isEmpty(publish_date_start)) {
            map["publish_date_start"] = "$publish_date_start"
        }
        if (!TextUtils.isEmpty(publish_date_end)) {
            map["publish_date_end"] = "$publish_date_end"
        }
        map["client"] = DataInvokeUtil.ClientFlag
        map["navigate_id"] = "$catalogID"
        map["page"] = "" + preLoadKit?.pageNum
        map["perPage"] = "" + pageSize


        DataInvokeUtil.ziMeiTiApi
            .getTimeLine(map)
            .subscribeOn(Schedulers.io())
            .map {
                preLoadKit?.hasMore = false
                val state = it.body()?.optBoolean("state") ?: false
                val dataList: MutableList<TimeLineItem> = ArrayList()
                if (state) {
                    it.body()?.optJSONObject("data")?.let {

                        MMKV.defaultMMKV()
                            .putString(XKey.CACHE_WS24_DATA + catalogID, it.toString())


                        val paging = it.optJSONObject("paging")
                        paging?.let {
                            preLoadKit?.hasMore = it.optInt("currentPage") < it.optInt("lastPage")
                            Log.e(
                                "XCXXXCCC",
                                "${preLoadKit?.hasMore} ${this@WS24ListFragment2.hashCode()}"
                            )
                        }
                        it.optJSONArray("meta")?.let {
                            val size = it.length()
                            for (i in 0 until size) {
                                val obj = it.optJSONObject(i)
                                val type = obj.optInt("type")
                                if (type == TypeX.NEWS.VIDEO || type == TypeX.NEWS.MICRO_LIVE || type == TypeX.NEWS.LITE_AV) {
                                    var video: JSONObject
                                    try {
                                        video = obj.optJSONObject("video")
                                    }catch (e:Exception){
                                        video = JSONObject("")
                                    }
                                    val videoItem = TimeLineItem(
                                        obj.optLong("id"),
                                        obj.optString("title"),
                                        obj.optString("publishdate"),
                                        obj.optString("publishdate_format"),
                                        type,
                                        obj.optString("logo"),
                                        obj.optString("prop4"),
                                        video.toString()
                                    )
                                    videoItem.author = obj.optString("Author")
                                    videoItem.referName = obj.optString("ReferName")
                                    videoItem.url = obj.optString("url")
                                    dataList.add(
                                        videoItem
                                    )
                                } else {
                                    val item = TimeLineItem(
                                        obj.optLong("id"),
                                        obj.optString("title"),
                                        obj.optString("publishdate"),
                                        obj.optString("publishdate_format"),
                                        type,
                                        obj.optString("logo"),
                                        obj.optString("prop4"),
                                        ""
                                    )
                                    item.author = obj.optString("Author")
                                    item.referName = obj.optString("ReferName")
                                    item.url = obj.optString("url")
                                    dataList.add(item)
                                }
                            }
                        }
                    }
                }

                var lastItem: TimeLineItem? = null
                adapter?.items?.let {
                    if (it.isNotEmpty()) {
                        lastItem = it[it.size - 1] as TimeLineItem?
                    }
                }
                buildGroup(dataList, lastItem)
            }.onErrorReturn { null }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<MutableList<Any>> {
                override fun onSubscribe(d: Disposable) {
                    mDisposable = d
                }

                override fun onNext(t: MutableList<Any>) {
                    if (isDispose) return
                    refreshLayout?.finishLoadMore()
                    preLoadKit?.preLoadData?.add(t)
                    setData(t)
                    if (parentFragment is IExposure) {
                        val iExposure = parentFragment as IExposure
                        iExposure.exposureArticles
                    }
                    Log.e(
                        "XCXXXCCC",
                        "2 ${preLoadKit?.hasMore} ${this@WS24ListFragment2.hashCode()}"
                    )
                    preLoadKit?.preload()
                    recyclerView?.postDelayed({
                        if (userVisibleHint || !hidden) {
                            mRVListVideoKit?.let {
                                try {
                                    mRVListVideoKit?.initPendingPlay()
                                } catch (e: Exception) {
                                    e.printStackTrace()
                                }
                            }
                        }
                    }, 1000)
                }

                override fun onError(e: Throwable) {
                    refreshLayout?.finishLoadMore()

                    /*if (adapter!!.data.size == 0) {
                        showStateView(TYPE_NO_CONTENT, false)
                    } else {
                        closeStateView()
                    }*/


                    closeStateView()
                    val cache = MMKV.defaultMMKV().getString(XKey.CACHE_WS24_DATA + catalogID, "")
                    if (!TextUtils.isEmpty(cache)) {
                        val dataList: MutableList<TimeLineItem> = ArrayList()
                        val jsonObject = JSONObject(cache)
                        jsonObject.optJSONArray("meta")?.let {
                            val size = it.length()
                            for (i in 0 until size) {
                                val obj = it.optJSONObject(i)
                                val type = obj.optInt("type")
                                if (type == TypeX.NEWS.VIDEO || type == TypeX.NEWS.MICRO_LIVE || type == TypeX.NEWS.LITE_AV) {
                                    var video: JSONObject
                                    try {
                                        video = obj.optJSONObject("video")
                                    }catch (e:Exception){
                                        video = JSONObject("")
                                    }
                                    val videoItem = TimeLineItem(
                                        obj.optLong("id"),
                                        obj.optString("title"),
                                        obj.optString("publishdate"),
                                        obj.optString("publishdate_format"),
                                        type,
                                        obj.optString("logo"),
                                        obj.optString("prop4"),
                                        video.toString()
                                    )
                                    videoItem.author = obj.optString("Author")
                                    videoItem.referName = obj.optString("ReferName")
                                    videoItem.url = obj.optString("url")
                                    dataList.add(
                                        videoItem
                                    )
                                } else {
                                    val item = TimeLineItem(
                                        obj.optLong("id"),
                                        obj.optString("title"),
                                        obj.optString("publishdate"),
                                        obj.optString("publishdate_format"),
                                        type,
                                        obj.optString("logo"),
                                        obj.optString("prop4"),
                                        ""
                                    )
                                    item.author = obj.optString("Author")
                                    item.referName = obj.optString("ReferName")
                                    item.url = obj.optString("url")
                                    dataList.add(
                                        item
                                    )
                                }
                            }
                        }
                        setData(buildGroup(dataList, null))

                    } else {
                        if (adapter!!.items.size == 0) {
                            showStateView(TYPE_NO_CONTENT, false)
                        } else {
                            closeStateView()
                        }
                    }

                }

                override fun onComplete() {
                }
            })
    }

    private val cachArticleItem = arrayListOf<JSONObject>()
    private val ids = StringBuffer()

    fun cache() {
        cachArticleItem.clear()
        ids.delete(0, ids.length)
        val data = if (ids.length < 10)
            adapter?.items?.subList(0, ids.length)
        else
            adapter?.items?.subList(0, 10)

        data?.forEach {

            if (it is TimeLineItem) {
                val timeLineItem = it as TimeLineItem
                if (timeLineItem.type == 1) {
                    if (ids.toString().isNotEmpty()) {
                        ids.append("," + timeLineItem.id)
                    } else {
                        ids.append(timeLineItem.id)
                    }
                    val articleItem = ArticleItem()
                    articleItem.id = timeLineItem.id
                    articleItem.type = timeLineItem.type
                    articleItem.title = timeLineItem.title
                    articleItem.publishdate = timeLineItem.publishdate
                    articleItem.logo = timeLineItem.logo
                    articleItem.content = ""
                    val toJson = Gson().toJson(articleItem)
                    val jsonObject = JSONObject(toJson)
                    cachArticleItem.add(jsonObject)
                }
            }
        }

//        for (j in cachArticleItem.indices) {
//            cachArticleItem[j].put("content", "<html><head><link rel=\"stylesheet\" type=\"text/css\" href=\"https://web.test.mjh.pladaily.com.cn/cms/rmt9502/css/cssbase.css\"><meta name = \"format-detection\" content = \"telephone=no\"><meta name=\"viewport\" content=\"width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no\"><style>@font-face{font-family: appfactoryClientFont;src: url(\"APPFACTORY_CLIENT_LOCAL_FONT_SRC\");}body * {font-family: appfactoryClientFont;word-wrap: break-word;}</style></head><body ><div style=\"font-size:18px;line-height:1.5;\" id=\"editWrap\"><p style=\"text-align:left;line-height:2;padding-top:5px;padding-bottom:5px;\"><span style=\"font-size: 18px;\"><span style=\"font-family: 宋体;\">中国航天日|弘扬航天精神 拥抱星辰大海</span></span></p><p style=\"text-align:left;line-height:2;padding-top:5px;padding-bottom:5px;\"><span style=\"font-size: 18px;\"><span style=\"font-family: 宋体;\">来源：中国军网</span></span><span style=\"font-size: 18px;\"><span style=\"font-family: 宋体;\"> 作者：赵晶晶 张硕 </span></span></p><p style=\"text-align:center;line-height:2;padding-top:5px;padding-bottom:5px;\"><img border=\"0\" style=\"max-width:100%;width: 553px; height: 782px;\" zcmsimagerela=\"103400\" src=\"https://web.test.mjh.pladaily.com.cn/cms/rmt9502/upload/Image/mrtp/2022/03/29/7623b710d06141b9bf2614dce7e777bb.png?picturesize=960x0\" alt=\"7623b710d06141b9bf2614dce7e777bb.png\"></p><p style=\"text-align:left;line-height:2;padding-top:5px;padding-bottom:5px;\"><span style=\"font-size: 18px;\"><span style=\"font-family: 宋体;\">今天，在“东方红一号”卫星成功发射50周年之际，我们迎来了第五个“中国航天日”。</span></span></p><p style=\"text-align:left;line-height:2;padding-top:5px;padding-bottom:5px;\"><span style=\"font-size: 18px;\"><span style=\"font-family: 宋体;\">从“两弹一星”到“载人航天”，从“北斗组网”到“嫦娥探月”，一代代航天工作者秉承航天精神，勇攀科技高峰，创造了中国航天事业发展的辉煌成就。</span></span></p><p style=\"text-align:left;line-height:2;padding-top:5px;padding-bottom:5px;\"><span style=\"font-size: 18px;\"><span style=\"font-family: 宋体;\">探索浩瀚宇宙，发展航天事业，建设航天强国，是我们不懈追求的航天梦。从航天大国到航天强国，我们的航天梦必将绚丽绽放！</span></span></p><p></p></div></body><script type=\"text/javascript\">const imgDefault = '';var imgEle = document.getElementsByTagName('img');for (var i = 0; i < imgEle.length; i++) {    imgEle[i].setAttribute('title', '');    if(imgEle[i].getAttribute('src') == ''){        imgEle[i].setAttribute('src', imgDefault);    }    imgEle[i].addEventListener(\"error\", function (e) {        var ele = e.target;        ele.src = imgDefault;        ele.onerror = null;    })}// video、audio去除所有的title属性var videoEle = document.getElementsByTagName('video');for (var i = 0; i < videoEle.length; i++) {    videoEle[i].setAttribute('title', '');}var audioEle = document.getElementsByTagName('audio');for (var i = 0; i < audioEle.length; i++) {    audioEle[i].setAttribute('title', '');}// 兼容安卓上面样式差异（莫名换行）  cssbase无法实现var sectionEle = document.querySelectorAll(\"section[powered-by]\");for (var i = 0; i < sectionEle.length; i++) {  if(sectionEle[i].children[0] && sectionEle[i].children[0].tagName == 'SECTION' && sectionEle[i].children[0].getAttribute('style') && sectionEle[i].children[0].getAttribute('style').indexOf('width: 50%;') > -1){    const styleStr = 'display: flex;' + sectionEle[i].getAttribute('style');    sectionEle[i].setAttribute('style', styleStr);  }}function setupWebViewJavascriptBridge(callback) {    if (window.WebViewJavascriptBridge) {        return callback(WebViewJavascriptBridge);    }    if (window.WVJBCallbacks) {        return window.WVJBCallbacks.push(callback);    }    window.WVJBCallbacks = [callback];    var WVJBIframe = document.createElement('iframe');    WVJBIframe.style.display = 'none';    WVJBIframe.src = 'https://__bridge_loaded__';    document.documentElement.appendChild(WVJBIframe);    setTimeout(function () {        document.documentElement.removeChild(WVJBIframe)    }, 0)}var userInfo = '';var sign = '';var act_id = \"\";var u = navigator.userAgent,    app = navigator.appVersion,    reqData = {};function userInfoMsg() {    if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) {        userInfo = JSON.parse(window.android.morefunObjcGetUserInfo(true));    } else if (!!u.match(/\\(i[^;]+;( U;)? CPU.+Mac OS X/) || u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1) {        setupWebViewJavascriptBridge(function (bridge) {            bridge.callHandler('morefunObjcGetUserInfo', { \"needLogin\": true }, function (response) {                userInfo = JSON.parse(response);            });        });    }}var timestamp = new Date().getTime().toString();timestamp = Number(timestamp.slice(0, -3));function userInfoSign() {    let data = userInfo;    reqData = {        act_id: act_id,        group_id: data.userInfo.groupId,        OpenID: data.userInfo.userid,        Timestamp: timestamp,        uid: data.userInfo.userid,        avatar: data.userInfo.avatar,        TenantID: data.tenantID,        SourceID: data.userInfo.platforms ? data.userInfo.platforms : data.userInfo.platform,        userid: data.userInfo.userid,        mobile: data.userInfo.mobile,        nickname: data.userInfo.nickname,        token: data.userInfo.token,        SecretKey: 'defaultAPP'    };    if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) {        sign = window.android.mfsign(JSON.stringify(reqData));    } else if (!!u.match(/\\(i[^;]+;( U;)? CPU.+Mac OS X/) || u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1) {        setupWebViewJavascriptBridge(function (bridge) {            bridge.callHandler('morefunObjcCallback', reqData, function (response) {                let sign1 = decodeURI(response);                let mfSignStr = sign1.split(\"&\");                for (var i = 0; i < mfSignStr.length; i++) {                    if (mfSignStr[i].split(\"=\")[0] == 'mfSign') {                        sign = unescape(mfSignStr[i].split(\"=\")[1]);                    }                }            });        });    }}window.addEventListener(    'message',    e => {        if (typeof e.data == 'object') {            if (e.data.key == 'activityWH') {                let actData = e.data.value;                document.getElementById(actData.actId).contentWindow.postMessage(                    {                        key: 'activityIsApp',                        value: 'true'                    },                    '*'                );                act_id = actData.actId;                $(\"#video_content\").find('iframe').each(function () {                    if ($(this).attr(\"id\") == act_id) {                        //window.confirm(JSON.stringify(actData));                        $(this).css({ \"width\": actData.width, \"height\": actData.height })                    }                });            } else if (e.data.key == 'activityLogin') {                let actData = e.data.value;                userInfoMsg();                setTimeout(function () {                    userInfoSign();                }, 100);                setTimeout(function () {                    userInfo.timestamp = timestamp;                    if (userInfo.userInfo.userid) {                        document.getElementById(actData).contentWindow.postMessage(                            {                                key: 'activityUserInfo',                                value: {                                    sign: sign,                                    userInfo: userInfo                                }                            },                            '*'                        );                    };                }, 200);            } else if (e.data.key == 'getUserId') {                let actData = e.data.value;                userInfoMsg();                setTimeout(function () {                    userInfoSign();                }, 100);                setTimeout(function () {                    userInfo.timestamp = timestamp;                    if (userInfo.userInfo.userid) {                        document.getElementById(actData).contentWindow.postMessage(                            {                                key: 'actUserInfo',                                value: {                                    isOnAPP: 'true',                                    userInfo: userInfo                                }                            },                            '*'                        );                    };                }, 200);            }        }    })</script></html>")
//        }
//        val s = Gson().toJson(cachArticleItem)
//        MMKV.mmkvWithID(cacheCatalogID).putString(XKey.DETAIL_CACHE, s)

        setContentData(ids.toString())
    }

    private fun setData(t: MutableList<Any>) {
        if (preLoadKit?.pageNum == 1) {
            adapter?.setDataItems(t)//setNewData(t)
            if (preLoadKit?.pageNum == 1 && t.size > 0) {
                recyclerView.scrollToPosition(0)
            }
        } else {
            adapter?.addItems(t)
        }
        cache()
        if (adapter!!.items.size == 0) {
            showStateView(TYPE_NO_CONTENT, false)
        } else {
            closeStateView()
        }
    }

    protected fun setContentData(ids: String) {
        val params: MutableMap<String, String> = HashMap()
        params["article_id"] = ids //获取文稿的详情信息
        DataInvokeUtil.ziMeiTiApi.getArticleContent(params)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<JSONObject?> {
                override fun onSubscribe(d: Disposable) {}
                override fun onNext(jsonObject: JSONObject) {
                    if (jsonObject.optBoolean("state")) {
                        val data = jsonObject.optJSONArray("data")
                        for (i in 0 until data.length()) {
                            try {
                                val json = JSONObject(data[i].toString())
                                val article_id = json.optString("article_id")
                                val content = json.optString("content")
                                for (j in cachArticleItem.indices) {
                                    if (article_id == cachArticleItem[j].optString("id")) {
                                        cachArticleItem[j].put("content", content)
                                    }
                                }
                            } catch (e: java.lang.Exception) {
                                e.printStackTrace()
                            }
                        }
                        MMKV.mmkvWithID(catalogID).clearAll()
                        val s = Gson().toJson(cachArticleItem)
                        MMKV.mmkvWithID(catalogID).putString(XKey.DETAIL_CACHE, s)
                    }
                }

                override fun onError(e: Throwable) {}
                override fun onComplete() {}
            })
    }

    var preloadDisposable: Disposable? = null
    private fun preload(preNum: Int) {
        val map: MutableMap<String, String> = HashMap()
        if (!TextUtils.isEmpty(publish_date_start)) {
            map["publish_date_start"] = "$publish_date_start"
        }
        if (!TextUtils.isEmpty(publish_date_end)) {
            map["publish_date_end"] = "$publish_date_end"
        }
        map["client"] = DataInvokeUtil.ClientFlag
        map["navigate_id"] = "$catalogID"
        map["page"] = "$preNum"
        map["perPage"] = "" + pageSize


        val d = DataInvokeUtil.ziMeiTiApi
            .getTimeLine(map)
            .map {
                preLoadKit?.hasMore = false
                val state = it.body()?.optBoolean("state") ?: false
                val dataList: MutableList<TimeLineItem> = ArrayList()
                if (state) {
                    it.body()?.optJSONObject("data")?.let {
                        val paging = it.optJSONObject("paging")
                        paging?.let {
                            preLoadKit?.hasMore = it.optInt("currentPage") < it.optInt("lastPage")
                        }
                        it.optJSONArray("meta")?.let {
                            val size = it.length()
                            for (i in 0 until size) {
                                val obj = it.optJSONObject(i)
                                val type = obj.optInt("type")
                                if (type == TypeX.NEWS.VIDEO || type == TypeX.NEWS.MICRO_LIVE || type == TypeX.NEWS.LITE_AV) {
                                    var video: JSONObject
                                    try {
                                        video = obj.optJSONObject("video")
                                    }catch (e:Exception){
                                        video = JSONObject("")
                                    }
                                    val videoItem = TimeLineItem(
                                        obj.optLong("id"),
                                        obj.optString("title"),
                                        obj.optString("publishdate"),
                                        obj.optString("publishdate_format"),
                                        type,
                                        obj.optString("logo"),
                                        obj.optString("prop4"),
                                        video.toString()
                                    )
                                    videoItem.author = obj.optString("Author")
                                    videoItem.referName = obj.optString("ReferName")
                                    videoItem.url = obj.optString("url")
                                    dataList.add(
                                        videoItem
                                    )

                                } else {
                                    val item = TimeLineItem(
                                        obj.optLong("id"),
                                        obj.optString("title"),
                                        obj.optString("publishdate"),
                                        obj.optString("publishdate_format"),
                                        type,
                                        obj.optString("logo"),
                                        obj.optString("prop4"),
                                        ""
                                    )
                                    item.author = obj.optString("Author")
                                    item.referName = obj.optString("ReferName")
                                    item.url = obj.optString("url")
                                    dataList.add(
                                        item
                                    )
                                }
                            }
                        }
                    }
                }

                var lastItem: TimeLineItem? = null
                adapter?.items?.let {
                    if (it.isNotEmpty()) {
                        lastItem = it[it.size - 1] as TimeLineItem?
                    }
                }
                buildGroup(dataList, lastItem)
            }.subscribeOn(Schedulers.io())
            .onErrorReturn { null }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<MutableList<Any>> {
                override fun onSubscribe(d: Disposable) {
                    preloadDisposable = d
                }

                override fun onNext(t: MutableList<Any>) {
                    preLoadKit?.onPreloadSuccess(t, preNum)
                }

                override fun onError(e: Throwable) {
                    preLoadKit?.onPreloadFail(preNum)
                }

                override fun onComplete() {

                }
            })
    }

    @Synchronized
    private fun buildGroup(
        list: MutableList<TimeLineItem>,
        lastItem: TimeLineItem? = null
    ): MutableList<Any> {
        val finalData: MutableList<Any> = ArrayList()
        var lastDate: String? = null
        lastItem?.let {
            try {
                lastDate = sdf1.format(sdf0.parse(it.publishdate)?.time)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        list.forEach {
            try {
                val time = sdf0.parse(it.publishdate)?.time ?: 0
                val date = sdf1.format(time)
                if (date != lastDate) {
                    val dateItem = WSDateItem(date)
                    lastDate = date
                    finalData.add(dateItem)
                    it.isGroupFirst = true
                }
                it.group_date_time = time
                it.group_date_time_fromat = sdf1.format(time)
                it.timeInnerTx = it.publishdate_format//sdf3.format(time)
                it.timeTitleTx = sdf4.format(time)
                if (it.type == TypeX.NEWS.VIDEO) {
                    it.itemTypes = 2
                } else if (it.type == TypeX.NEWS.MICRO_VIDEO || it.type == TypeX.NEWS.LITE_AV) {
                    it.itemTypes = 3
                }
                finalData.add(it)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return finalData
    }


    override fun onLoadMore(refreshLayout: RefreshLayout) {
        Log.w(ListPreLoadKit.LTAG, "触发了 RefreshLayout onLoadMore")
        preLoadKit?.getMoreDate()
    }

    override fun onDestroyView() {
        if (recyclerView != null && scrollListener != null) {
            recyclerView.removeOnScrollListener(scrollListener!!)
        }
        //  refreshLayout = null


        super.onDestroyView()
    }

    override fun getExposureArticles(): MutableList<ArticleItem>? {
        val data = adapter?.items
        var mExposureArticles: MutableList<ArticleItem>? = null
        if (data == null) return mExposureArticles
        try {
            val childCount = recyclerView.childCount
            for (i in 0 until childCount) {
                val view = recyclerView.getChildAt(i)
                view?.let {
                    if (TXReportManager.getVisibility(it)) {
                        val position = recyclerView.getChildAdapterPosition(view)
                        val _item = data[position]
                        if (_item is TimeLineItem) {
                            val item = ArticleItem()
                            item.id = _item.id
                            item.title = _item.title
                            item.publishdate = _item.publishdate
                            item.publishdate_format = _item.publishdate_format
                            item.type = _item.type
                            item.logo = _item.logo
                            item.prop4 = _item.prop4
                            item.positionInList = position
                            item.parentId = catalogID
                            item.Author = _item.author
                            item.referName = _item.referName
                            if (mExposureArticles == null) {
                                mExposureArticles = ArrayList()
                            }
                            mExposureArticles?.add(item)
                        }
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return mExposureArticles
    }

    override fun getExposureComponentItem(): ComponentItem? {
        return null
    }


    fun choosed() {
        recyclerView?.postDelayed({
            mRVListVideoKit?.pendingStopPlay = false
            mRVListVideoKit?.mDy = 1
            mRVListVideoKit?.initPendingPlay()
        }, 800)

    }

    fun unChoose() {
        mRVListVideoKit?.stopPlay()
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (!userVisibleHint) {
            mRVListVideoKit?.stopPlay()
        } else {
            recyclerView?.postDelayed({
                mRVListVideoKit?.pendingStopPlay = false
                mRVListVideoKit?.initPendingPlay()
            }, 800)
        }
    }


    var hidden: Boolean = true;
    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        this.hidden = hidden
        if (hidden) {
            mRVListVideoKit?.stopPlay()
        }
    }

    override fun onDestroy() {
        mRVListVideoKit?.onDestroy()
        super.onDestroy()
    }

}